package alejandro.castro.controllers;

import java.util.LinkedList;
import java.util.List;

import alejandro.castro.abstracts.AsteroidGameComponent;
import alejandro.castro.asteroid.components.Asteroid;
import alejandro.castro.asteroid.components.Shot;

import com.uqbar.vainilla.DeltaState;

public class CollisionController extends AsteroidGameComponent {

	List<Asteroid> removedAsteroids;
	List<Shot> removedShots;

	public CollisionController() {
		super(0, 0);
		removedAsteroids = new LinkedList<Asteroid>();
		removedShots =  new LinkedList<Shot>();
	}
	
	
	@Override
	public void update(DeltaState deltaState) {		
		super.update(deltaState);
		try {
			this.getScene().componentsAdding.acquire();
			for (Asteroid asteroid : getAteroids()) {
				checkWith(asteroid);
			}
			this.getScene().removeAsteroids(removedAsteroids);
			this.getScene().removeShots(removedShots);
			this.getScene().componentsAdding.release();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		for (Asteroid asteroid : removedAsteroids) {
			asteroid.hasBeenDestroyed();
		}
		removedAsteroids.clear();
		removedShots.clear();
		
	}

	private void checkWith(Asteroid asteroid) {
		for (Shot shot : getShots()) {
			if(shot.collidesWith(asteroid)){
				this.removedShots.add(shot);
				this.removedAsteroids.add(asteroid);
			}
		}
	}

	private List<Shot> getShots() {		
		return this.getScene().getShots();
	}

	private List<Asteroid> getAteroids() {
		return this.getScene().getAsteroids();
	}

}
